package controllers;

import play.*;
import play.libs.Codec;
import play.mvc.*;
import play.data.validation.*;

import java.util.*;

import notifiers.*;

import controllers.Security;

import models.*;

public class Application extends Controller {

    public static void index() {
    	User user = Security.getConnected();
    	if(user == null) {
        	List<NewsItem> news = NewsItem.getMainNews();
    		render(news);
    	} else
    		Courses.index();
    }
    
    //TODO: Login-Fehler-Ausgabe
    public static void register(@Required @Email String email, 
    							@Required String username, 
    							String realname, 
    							@Required @MinSize(5) String password, 
    							@Required @Equals("password") String passwordRepeat) {
    	
    	//If the form contains erros or the mailadress is already taken display error messages
    	if (validation.hasErrors() || !User.isEmailAvailable(email) || !User.isUsernameAvailable(username)) {
    		if (!User.isEmailAvailable(email))
        		flash.put("mailError", "Sorry, but this adress is already in use.");
    		
    		if (!User.isUsernameAvailable(username))
    			flash.put("nameError", "Sorry, but this name is already taken.");
    		
            validation.keep();
            params.flash();
            flash.error("Please correct these errors !");
            index();
        }
    	User user = new User(email, password, username);
    	user.realname = realname;
    	user.save();
    	try {
			Notifier.welcome(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	index();
    }
    
    public static void confirmRegistration(String uuid) {
        User user = User.findByRegistrationUUID(uuid);
        notFoundIfNull(user);
        user.needConfirmation = null;
        user.save();
        flash.success("Welcome %s ! You may now login", user.name);
        index();
    }

}